from fastapi import Depends, Header
from jwt.exceptions import InvalidTokenError
from fastapi.security import OAuth2PasswordBearer
from utils.encryAbout import decode_token, checkck_token
from schema.response.baseResponse import CustomException


# 定义全局中间件进行token验证 (这种方式需要 有一个token接口<swagger UI 模式用户名，密码 通过token接口获取token>，因为自定了返回格式且路径不一致)
# oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


# def decode_token_by_head(token: str = Depends(oauth2_scheme)):
#     try:
#         plain_token = checkck_token(token)
#         if not plain_token:
#             raise CustomException(401, "token失效")
#         return plain_token
#     except InvalidTokenError:
#         raise CustomException(401, "token失效")


# 这是配置swagger 的参数 ， 或者 直接修改header 参数为我token 在每个接口进行传递 不需要main.py 的custom_openapi
def decode_token_by_head(authorization: str = Header(None)):
    try:
        if not authorization or not authorization.startswith("Bearer"):
            raise CustomException(401, "token失效")
        token = authorization.split("Bearer ")[1]
        plain_token = checkck_token(token)
        if not plain_token:
            raise CustomException(401, "token失效")
        return plain_token
    except InvalidTokenError:
        raise CustomException(401, "token失效")
    
